<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>购物车</title>
    <link rel="stylesheet" href="../css/header.css">
    <link rel="stylesheet" href="../css/footer.css">
    <link rel="stylesheet" href="../css/cart.css">
    <link rel="stylesheet" href="../css/bootstrap.css">
    <link rel="stylesheet" href="../css/css_pc_init.css">
</head>

<body>
    <header>
        <div class="header">
            <div class="header-nav">
                <h1 class="header-logo">
                    <a href="index.html">
                        <img src="../images/logo.png" alt="21cake logo" />
                    </a>
                </h1>
                <ul class="nav-box">
                    <li><a href="index.html">首页</a></li>
                    <li><a href="cake.html" target="_self">蛋糕</a></li>
                    <li><a href="bread.html" target="_self">面包</a></li>
                    <li><a href="ice-cream.html" target="_self">冰淇淋</a></li>
                    <li><a href="coffee-tea.html" target="_self">咖啡下午茶</a></li>
                    <li><a target="_self">咖啡全国送</a></li>
                    <li><a target="_self">企业专区</a></li>
                </ul>
                <div class="right-city-user">
                    <a class="header-app app-download">APP下载</a>
                    <div class="current-city">上海<i></i></div>
                    <a class="header-message">消息</a>
                    <span class="not-login"><a href="login.html">登录</a>/<a href="register.html">注册</a></span>
                    <a class="header-user">
                        <img src="../images/user-img.png" alt="21cake user icon" />
                    </a>
                    <a href="cart.html" class="header-cart">
                        <i></i>
                    </a>
                    <ul class="current-city-list  header-select">
                        <li><a href="javascript:void(0);" class="city-id-1">上海</a></li>
                        <li><a href="javascript:void(0);" class="city-id-2">北京</a></li>
                        <li><a href="javascript:void(0);" class="city-id-3">天津</a></li>
                        <li><a href="javascript:void(0);" class="city-id-4">杭州</a></li>
                        <li><a href="javascript:void(0);" class="city-id-5">无锡</a></li>
                        <li><a href="javascript:void(0);" class="city-id-6">苏州</a></li>
                        <li><a href="javascript:void(0);" class="city-id-7">广州</a></li>
                        <li><a href="javascript:void(0);" class="city-id-8">深圳</a></li>
                    </ul>
                    <ul class="header-user-list  header-select">
                        <li><a target="_blank">我的订单</a></li>
                        <li><a target="_blank">我的优惠券</a></li>
                        <li><a target="_blank">我的纪念日</a></li>
                        <li><a class="logout" target="_self">退出登录</a></li>
                    </ul>
                    <ul class="message-list-header  header-select">
                        <li><a target="_blank">通知</a></li>
                        <li><a target="_blank">物流</a></li>
                    </ul>
                    <dl class="app-list  header-select">
                        <dt>
                            <img src="../images/footer-erweima.png" alt="下载APP" />
                        </dt>
                        <dd>下载享更多优惠</dd>
                    </dl>
                </div>
            </div>
        </div>
    </header>

    <div class="content-box">
        <div class="cart-not-pro cl">
            <img src="../images/cartempty.png">
            <span>您的购物车里还没有商品</span>
            <a href="index.html">去购物 &gt;&gt;</a>
        </div>
        <!-- 商品信息 -->
        <div class="cart-goods-info cart-area cart-list">
            <ul class="thead-ul">
                <li class="check-all"><input type="checkbox" checked></li>
                <li class="goods-ti">商品</li>
                <li class="birthday-card-ti">生日牌</li>
                <li class="unit-Price">单价</li>
                <li class="number-ti">数量</li>
                <li class="money-ti" colspan="2">金额</li>
            </ul>

            <div class="tbody-ul">
                <table>
                    <!-- 普通商品开始 -->
                    <tbody>
                        <tr>
                            <td colspan="8" class="tableware-list">
                                <ul>
                                    <li class="tableware-row">
                                        <img src="../images/3942d4bcfd0d09f48714a9f5b5997290.jpg" alt="方形蜡烛">
                                        <div class="right-title">
                                            <h5>方形蜡烛<span>配件</span></h5>
                                            <span>￥8.00</span>
                                            <a href="#" class="action-add-to-cart part1" title="加入购物车"><i></i></a>
                                        </div>
                                    </li>
                                    <li class="tableware-row">
                                        <img src="../images/84ea7dbb64e18846e0bcdf22172671ae.jpg" alt="餐具套餐">
                                        <div class="right-title">
                                            <h5>餐具套餐<span>配件</span></h5>
                                            <span>￥0.50</span>
                                            <a href="#" class="action-add-to-cart part2" title="加入购物车"><i></i></a>
                                        </div>
                                    </li>
                                </ul>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="cart-submit cart-area">
            <a href="#" class="cart-submit-empty"><i></i>批量删除</a>
            <ul class="cart-total-detail">
                <li>商品金额：¥ <strong></strong></li>
                <li>配送费：¥ <strong>00.00</strong></li>
                <li>活动优惠：¥ <strong>00.00</strong></li>
            </ul>
            <div class="cart-total"><span>合计：¥<span></span></span></div>
            <span class="cart-balance"></span>
            <div class="cart-submit-button"><a href="javascript:void(0);">去结算</a></div>
        </div>
    </div>

    <footer>
        <div class="footer">
            <img class="footer-logo" src="../images/footer-logo.png" height="36" width="96" alt="">
            <div class="footer-nav">
                <a>联系我们</a>
                <span>|</span>
                <a>订购帮助</a>
                <span>|</span>
                <a>企业合作</a>
                <span>|</span>
                <a>生产经营资质</a>
                <span>|</span>
                <a>公告专区</a>
            </div>
            <div class="footer-icon">
                <a href="http://weibo.com/21cake" target="_blank">
                    <img src="../images/footericon-01.png">
                </a>
                <a class="footer-weixin">
                    <div class="footer-erweima footer-weixin-erweima">
                        <img src="../images/erweima.png">
                    </div>
                    <img src="../images/footericon-02.png">
                </a>
                <a class="footer-app">
                    <div class="footer-erweima footer-app-erweima">
                        <img src="../images/footer-erweima.png">
                    </div>
                    APP
                </a>
            </div>

            <div class="footer-text">
                <span>订购专线：400 650 2121（服务时间 08:00–22:00）</span>
                <span>客服电话：021-23099721（全国） | kefu@21cake.com（邮箱）</span>
                <span>杭州/广州：提前5小时预订；北京：提前6小时预订；上海：提前5.5-6小时预订；天津/苏州/无锡/深圳：提前8小时预订（部分偏远地区除外，当日22点以后订单，于次日8点开始审核） </span>
                <span>当日蛋糕配送截止下单时间：北京：16:50；上海：16:30；杭州/广州：13:50；天津：10:30；苏州/无锡/深圳：11:00</span>
                <span>网站注册公司名称: 北京廿一客食品有限公司 地址: 北京市北京经济技术开发区兴海二街5号院3号楼 </span>
            </div>
            <div class="footer-copyright">
                <span>Copyright© 21Cake蛋糕官网商城 2007-2018, 版权所有 <a style="color: #9a9a9a" target="_blank" href="http://www.miitbeian.gov.cn/">京ICP备14006254号-1</a></span>
            </div>
        </div>
    </footer>
</body>
<script src="../js/jquery.js"></script>
<script src="../js/bootstrap.js"></script>
<script src="../js/header.js"></script>
<script src="../js/login.js"></script>
<script src="../js/cookie.js"></script>
<script>
    //头部的显隐事件
    header();
    //登录事件
    login();

    if (!getCookie("t_cake_userId")) {
        location.href = "login.html";
    }

    //配件点击事件
    $(".tableware-list .action-add-to-cart").click(function () {
        if ($(this).hasClass("part1")) {
            addShoppingCart("", "part1", "20", 1);
            cartData();
        } else if ($(this).hasClass("part2")) {
            addShoppingCart("", "part2", "21", 1);
            cartData();
        }
    });

    var checkOneCount = $(".check").length;
    cartData();
    function cartData() {
        let html = "";
        $.ajax({
            type: "get",
            url: "../php/cartbyid.php",
            data: {
                userid: getCookie("t_cake_userId")
            },
            dataType: "json",
            success: function (list) {
                if (list.length === 0) {
                    $(".cart-not-pro").show();
                    $(".cart-goods-info").hide();
                    $(".cart-submit").hide();
                } else {
                    $(".cart-not-pro").hide();
                    $(".cart-goods-info").show();
                    $(".cart-submit").show();
                    for (var attr in list) {
                        let id = list[attr]["id"];
                        let goodsid = list[attr]["goodsid"];
                        let goodsnum = list[attr]["goodsnum"];
                        let birthday_card = list[attr]["birthday_card"];
                        let measure = list[attr]["measure"];
                        let mount = list[attr]["mount"];
                        let goods_name = list[attr]["goods_name"];
                        let goods_smallimg = list[attr]["goods_smallimg"];
                        let goodsprice = list[attr]["goodsprice"];
                        let goods_type = list[attr]["goods_type"];
                        let measure_id = list[attr]["measure_id"];
                        let total = goodsprice * goodsnum;

                        html += `
                <tr class="cart-object-item scene_area">
                    <td><input type="checkbox" class="check" onclick="checkClick(this)" data-goodsid="${goodsid}" data-measure="${measure_id}" checked></td>
                    <td class="goods-img">
                        <a href="goods-details.html?goods_id=${goodsid}" target="_blank">
                            <img src="../images/${goods_smallimg}">
                        </a>
                    </td>
                    <td class="goods-cake">
                        <div>
                            <h4 class="cart-title">
                                <a href="goods-details.html?goods_id=${goodsid}" target="_blank">${goods_name}</a>
                            </h4>
                            <span class="goods-spec">规格：<span>${measure}</span></span>
                            <span class="goods-laid"><i></i>${mount}</span>
                        </div>
                    </td>
                    <td class="select-birthday-td" data-type="${goods_type}">
                        <div class="select-birthday">
                            <div class="action-birthday_card active" data-goodsid='${goodsid}' data-measure='${measure_id}'>${birthday_card}<i></i></div>
                            <ul class="action-birthday-options">
                                <li class="birthday-card-option">元旦快乐</li>
                                <li class="birthday-card-option">新年快乐</li>
                                <li class="birthday-card-option">Happy New Year</li>
                                <li class="birthday-card-option">生日快乐</li>
                                <li class="birthday-card-option">Happy Birthday</li>
                                <li class="birthday-card-option">节日快乐</li>
                                <li class="brith_card_by_self">自定义</li>
                                <li class="action-input-container">
                                    <input type="text" placeholder="可输入8个汉字或16个字符">
                                    <input type="button" value="确定" class="action-birth-card-btn">
                                </li>
                            </ul>
                        </div>
                    </td>
                    <td class="cart-unit-Price">¥${goodsprice}</td>
                    <td class="number-li">
                        <div class="number quantity-update">
                            <input type="button" class="minus" onclick="reduceClick(this)" data-goodsid="${goodsid}">
                            <input type="text" class="quantity _quantity" value="${goodsnum}" readonly>
                            <input type="button" class="plus" onclick="addClick(this)" data-goodsid="${goodsid}">
                        </div>
                    </td>
                    <td class="money">￥${total.toFixed(2)}</td>
                    <td class="delete" onclick="deleteClick(this)" data-goodsid="${goodsid}"><a href="#"><i></i></a></td>
                </tr>
                        <!-- 普通商品结束 -->
                `;
                    }
                    $(".tbody-ul tbody tr.cart-object-item").html("");
                    $(".tbody-ul tbody").prepend(html);
                    $("[data-type]:not([data-type='蛋糕'])").html("");
                    checkOneCount = $(".check").length;

                    //减号判断事件
                    $(".quantity").each(function(index,item){
                        if($(item).val() == "1"){
                            $(item).prev().prop("disabled", true);
                        }
                    });
                    //购物车事件
                    $(document).click(function () {
                        $(".action-birthday-options").hide();
                    });
                    $("table .action-birthday_card").click(function (e) {
                        var that = this;
                        e.stopPropagation();
                        $(this).next().show();
                        $(this).next().find("li").click(function (e) {
                            e.stopPropagation();
                            if ($(this).html() === "自定义") {
                                $(this).next().show();
                                $(this).next().children().eq(0).val("");
                                $(this).hide();
                                $(".action-birth-card-btn").click(function (e) {
                                    e.stopPropagation();
                                    $(that).html($(this).prev().val() + "<i></i>");
                                    addShoppingCart($(this).prev().val(), $(that).attr("data-goodsid"), $(that).attr("data-measure"), 0)
                                    $(this).parent().prev().show();
                                    $(this).parent().hide();
                                    $(that).next().hide();
                                });
                            } else if ($(this).hasClass("birthday-card-option")) {
                                $(that).html($(this).html() + "<i></i>");
                                addShoppingCart($(this).html(), $(that).attr("data-goodsid"), $(that).attr("data-measure"), 0)
                                $(that).next().hide();
                            }
                        });
                    });

                    getTotal();
                }
            }
        });
    }

    //购物车更新数量
    function updateGoodsCount(goodsid, goodsnum) {
        $.ajax({
            type: "get",
            url: "../php/update_cart_num.php",
            data: {
                userid: getCookie("t_cake_userId"),
                goodsid: goodsid,
                goodsnum: goodsnum
            },
            dataType: "json",
            success: function (obj) {
            }
        });
    }

    //加号处理
    function addClick(obj) {
        $(obj).prev().prev().removeAttr("disabled");
        $(obj).prev().val($(obj).prev().val() * 1 + 1);
        let price = $(obj).parent().parent().prev().html().substring(1);
        $(obj).parent().parent().next().html("￥" + (price * $(obj).prev().val()).toFixed(2));
        getTotal();
        updateGoodsCount($(obj).attr("data-goodsid"), 1);
    }

    //减号处理
    function reduceClick(obj) {
        if ($(obj).next().val() <= 1) {
            $(obj).prop("disabled", true);
            return;
        }
        $(obj).next().val($(obj).next().val() * 1 - 1);
        let price = $(obj).parent().parent().prev().html().substring(1);
        $(obj).parent().parent().next().html("￥" + (price * $(obj).next().val()).toFixed(2));
        getTotal();
        updateGoodsCount($(obj).attr("data-goodsid"), -1);
    }

    //单选和全选
    
    $(".check-all input").click(function () {
        var flag = $(this).is(":checked");
        for (var i = 0; i < $(".check").length; i++) {
            if (flag) {
                $(".check").eq(i).prop("checked", flag);
            } else {
                $(".check").eq(i).prop("checked", flag);
            }
        }
        checkOneCount = flag ? $(".check").length : 0;
        getTotal();
    });

    function checkClick(obj) {
        if ($(obj).is(":checked")) {
            checkOneCount++;
        } else {
            checkOneCount--;
        }
        if (checkOneCount === $(".check").length) {
            $(".check-all input").prop("checked", "checked");
        } else {
            $(".check-all input").prop("checked", false);
        }
        getTotal();
    }

    function deleteData(goodsId) {
        $.ajax({
            type: "get",
            url: "../php/delete_cart.php",
            data: {
                userid: getCookie("t_cake_userId"),
                goodsid: goodsId
            },
            dataType: "json",
            success: function (obj) {
            }
        });
    }
    //单个删除
    function deleteClick(obj) {
        deleteData($(obj).attr("data-goodsid"));
        if ($(obj).parent().first().children().is(":checked")) {
            checkOneCount--;
        }
        $(obj).parent().remove();
        getTotal();
        cartData();
    }

    //批量删除
    $(".cart-submit-empty").click(function () {
        for (var i = 0; i < $(".check").length; i++) {
            if ($(".check").eq(i).is(":checked")) {
                deleteData($(".check").eq(i).attr("data-goodsid"));
            }
        }
        for (var i = 0; i < $(".check").length; i++) {
            if ($(".check").eq(i).is(":checked")) {
                $(".check").eq(i).parent().parent().remove();
                i--;
            }
        }
        getTotal();
        checkOneCount = $(".check").length;
        $(".check-all input").prop("checked", "checked");
        cartData();
    });

    //***数据处理及更新
    function getTotal() {
        let sumTotal = 0;
        let countTotal = 0;
        let amountTotal = 0;
        for (var i = 0; i < $(".check").length; i++) {
            if ($(".check").eq(i).is(':checked')) {
                let price = $(".check").eq(i).parent().parent().children().eq(4).html().substring(1);
                let count = $(".check").eq(i).parent().parent().children().eq(5).children().children().eq(1).val();
                countTotal += count * 1;
                sumTotal += count * price;
            }
        }
        $(".cart-total-detail strong").eq(0).html(sumTotal.toFixed(2));
        $(".cart-total span").eq(1).html((sumTotal + $(".cart-total-detail strong").eq(1).html() * 1 + $(".cart-total-detail strong").eq(2).html() * 1).toFixed(2));
        if ($(".cart-total span").eq(1).html() * 1 >= 100) {
            $(".cart-balance").html(`订单已满￥100元,享免费配送服务`);
        } else if ($(".cart-total span").eq(1).html() * 1 > 0) {
            $(".cart-balance").html(`满￥100元,享免费配送服务,还差￥${100 - $(".cart-total span").eq(1).html()}元 <a href="index.html" style="margin-left:8px;">去加购 &gt;&gt;</a>`);
        } else if ($(".cart-total span").eq(1).html() * 1 == 0) {
            $(".cart-balance").html(`<span style="color:red;">请选择商品</span>`);
        }
    }

    function addShoppingCart(birthday_card, goods_id, measure_id, goodsnum) {
        if (getCookie("t_cake_userId")) {
            $.ajax({
                type: "get",
                url: "../php/addcart.php",
                data: {
                    userid: getCookie("t_cake_userId"),
                    goodsid: goods_id,
                    measure_id: measure_id,
                    birthday_card: birthday_card,
                    goodsnum: goodsnum
                },
                dataType: "json",
                success: function (obj) {
                }
            });
        } else {
            setCookie("historyURL",location.href,7);
            location.href = "login.html";
        }
    }

    $(".cart-submit-button").click(function () {
        if ($(".cart-total span").eq(1).html() * 1 > 0) {
            for (var i = 0; i < $(".check").length; i++) {
                if ($(".check").eq(i).is(":checked")) {
                    $.ajax({
                        type: "get",
                        url: "../php/add_order.php",
                        data: {
                            userid: getCookie("t_cake_userId"),
                            goodsid: $(".check").eq(i).attr("data-goodsid"),
                            goodsnum: $(".quantity").eq(i).val(),
                            measure_id: $(".check").eq(i).attr("data-measure"),
                            birthday_card: $(".select-birthday-td").eq(i).children().children().first().text()
                        },
                        dataType: "json",
                        success: function (obj) {
                            location.href = "cart-checkout.html";
                        }
                    });
                }
            }
        }
    });
</script>

</html>